import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue'),
        name: '小U商城'
      }, {
        path: '/cate',
        component: () => import('../views/cate.vue'),
        name: '分类'
      },
      {
        path: '/shopping',
        component: () => import('../views/shopping.vue'),
        name: '购物车'
      }, {
        path: '/mine',
        component: () => import('../views/mine.vue'),
        name: '我的'
      },
      {
        path: '',
        redirect: '/home'
      }
    ],
  },
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/register',
    component: () => import('../pages/register.vue')
  },
  {
    path: '/address',
    component: () => import('../pages/address.vue'),
    name: '地址管理'
  },
  {
    path: '/detail/:id',
    component: () => import('../pages/detail.vue'),
    name: '商品详情'
  },
  {
    path: '/catelist/:id',
    component: () => import('../pages/catelist.vue'),
    name: '商品列表'
  },
  {
    path: '/searchlist/:id',
    component: () => import('../pages/searchlist.vue'),
    name: '商品搜索'
  },
  {
    path: '*',
    redirect: '/home'
  }
]

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior(to, from, position) {
    if (position) {
      return position
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  }
})

router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next()
    return
  }
  if (to.path == '/register') {
    next()
    return
  }
  if (sessionStorage.getItem('islogin')) {
    next()
    return
  }
  next('/login')
})

export default router
